package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    // 请求进入时进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //System.out.println(handler.getClass().getName() +"拦截到的请求对象 前=" + handler);

        // 解决拦截器跨域
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 判断当前请求的映射方法是否需要登录 @RequireLogin
        HandlerMethod hm = (HandlerMethod)handler;

        //System.out.println(handler.getClass().getName() +"拦截到的请求对象 后=" + hm);

        // 每次请求都要重置登录状态
        // 不管该请求是否需要登录
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        if (hm.hasMethodAnnotation(RequireLogin.class)) {

            if (user == null) {
                // 没登录
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }

        }

        return true;
    }
}
